package com.dcits.electronic_account.controller;

import com.alibaba.fastjson.JSON;
import com.dcits.electronic_account.bean.BankAccount;
import com.dcits.electronic_account.bean.ResponseJson;
import com.dcits.electronic_account.bean.VirtualAccount;
import com.dcits.electronic_account.constant.Constant;
import com.dcits.electronic_account.service.RechargeService;
import com.dcits.electronic_account.utils.MD5Util;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;

/**
 * @author: YHC
 * @Date: 2022/6/25
 */
@RequestMapping("/recharge")
@RestController
public class RechargeController {

    @Resource
    RechargeService rechargeService;


    @RequestMapping("/rechargeDo")
    ResponseJson rechargeDo(@RequestBody String data){
        //处理传输来的数据
        Integer userId = Integer.valueOf(JSON.parseObject(data).get("userId").toString());
        String cardNumber = JSON.parseObject(data).get("cardNumber").toString();
        BigDecimal amount = new BigDecimal(JSON.parseObject(data).get("amount").toString());
        String payPwd = JSON.parseObject(data).get("payPwd").toString();

        VirtualAccount virtualAccount = rechargeService.searchVirByUserId(userId);
        BankAccount bankAccount = rechargeService.searchBankByNumber(cardNumber);

        String checkPayPwd = MD5Util.getMd5(payPwd);

        //数据校验
        if(!checkPayPwd.equals(virtualAccount.getPayPwd())) return new ResponseJson(500,"支付密码错误");
        if(amount.compareTo(BigDecimal.ZERO)<=0) return new ResponseJson(Constant.FAIL_CODE,"金额输入有误");
        if(bankAccount.getBalance().subtract(amount).compareTo(BigDecimal.ZERO)<0) return new ResponseJson(500,"银行卡余额不足");

        //进行充值
        try {
            rechargeService.rechargeDo(virtualAccount,bankAccount,amount);
            return new ResponseJson(200,"充值成功");
        } catch (Exception e) {
            return new ResponseJson(500,"操作异常，充值失败");
        }

    }

}
